package com.yunpai.thread;

/**
 * 模拟次窗口卖票案列 实现Runnable的方式 与方法方法
 */
public class WindRunnableTicketTypeTwo implements Runnable {
    static int ticket = 100;
    //代码块锁
    Object o = new Object();

    @Override
    public void run() {
        while (true) {
            method();
        }
    }

    //添加代码块
    public synchronized void method() {  //同步监视器为当前的this对象

        if (ticket > 0)
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        System.out.println(Thread.currentThread().getName() + "卖的是第" + ticket + "张");
        ticket--;
    }


    public static void main(String[] args) {
        WindRunnableTicketTypeOne windows = new WindRunnableTicketTypeOne();
        //窗口一
        Thread wid1 = new Thread(windows);
        //窗口二
        Thread wid2 = new Thread(windows);
        //窗口三
        Thread wid3 = new Thread(windows);
        wid1.setName("窗口一");
        wid2.setName("窗口二");
        wid3.setName("窗口三");
        wid1.start();
        wid2.start();
        wid3.start();
    }
}
